package com.hurl.waguji.web.cx;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.hurl.library.util.DateUtils;
import com.hurl.library.util.StringUtils;
import com.hurl.waguji.base.DateService;
import com.hurl.waguji.base.dao.HibernateDao;
import com.hurl.waguji.base.dao.HibernateService;
import com.hurl.waguji.persistence.PhConfigBO;
import com.opensymphony.xwork2.ActionSupport;

public class PhAction extends ActionSupport {
	private List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
	private Map<String,Object> queryResults = new HashMap<String,Object>();
	private String rq = null;
	private String fl = null;
	private Integer id;
	
	public List<Map<String,Object>> getList(){
		return this.list;
	}
	public String getFl(){
		return this.fl;
	}
	public void setFl(String fl){
		this.fl = fl;
	}
	public Integer getId(){
		return id;
	}
	public void setId(Integer id){
		this.id = id;
	}
	
	public String getRq(){
		return this.rq;
	}
	public void setRq(String rq){
		this.rq = rq;
	}
	public Map<String,Object> getQueryResults(){
		return queryResults;
	}
	
	public String execute()throws Exception{
		HibernateDao dao = HibernateService.getDao();
		if(StringUtils.isBlank(this.rq)){
			this.rq = DateUtils.formatDate(DateService.getLastTradingTimeFromServer(), DateUtils.FORMAT_DATE);
		}
		List<PhConfigBO> configList = (List<PhConfigBO>)dao.createCriteria(PhConfigBO.class).add(Restrictions.eq("fl", this.getFl())).addOrder(Order.asc("sx")).list();
		if(configList!=null && !configList.isEmpty()){
			for(PhConfigBO config : configList){
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("colConfig", config.getColConfig().split(","));
				map.put("title", config.getTitle());
				map.put("id", config.getId());
				list.add(map);
			}
		}
		return SUCCESS;
	}
	public String query() throws Exception{
		if(id==null){
			return SUCCESS;
		}
		
		HibernateDao dao = HibernateService.getDao();
		
		/* 取得该项排行的配置信息 */
		PhConfigBO config = dao.load(PhConfigBO.class, id);
		if(config==null){
			return SUCCESS;
		}
		/* 取得查询SQL */
		String sql = config.getSql();
		sql = sql.replace("?", rq);

		String colConfig = config.getColConfig();
		String[] names = colConfig.split(",");
		List<Map<String,Object>> root = new ArrayList<Map<String,Object>>();
		int totalProperty = 0;
		/* 查询并保存输入到root */
		List<Object[]> list = dao.queryBySQL(sql).setReadOnly(true).setFetchSize(10).list();
		for(Object[] row : list){
			Map<String,Object> rowmap = new HashMap<String,Object>();
			for(int i=0;i<names.length;i++){
				rowmap.put("col"+i, row[i]);
			}
			root.add(rowmap);
			totalProperty++;
		}
		queryResults.put("totalProperty", totalProperty);
		queryResults.put("root", root);
		
		return SUCCESS;
	}
}
